<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\Goods;
use App\Http\Model\User;
use App\Http\Model\Menu;
use DB;

class WeixinController extends Controller{
    private $appid='wx0ed7a32cb54a40d7';
    private $appsecret='df3d04c9971f454f73812b76b8092676';
    private $TOKEN='weixin';
    public function index(Request $request){
        if(!isset($_GET['echostr'])){
            //响应消息
            $this->responseMsg();
        }else{
            //验证消息
            $this->valid();
        }
        $post = '{
             "button":[
              {
                    "name":"商城",
                    "sub_button":[
                    {
                        "type":"view",
                        "name":"天路本草",
                        "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0ed7a32cb54a40d7&redirect_uri=http://www.gengyong.com.cn/&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/"
                    },
                    {
                        "type":"view",
                        "name":"微商城",
                        "url":"http://www.wangzhihao.net.cn:8008/"
                    }]
              },
              {
               "name":"联系我们",
                   "sub_button":[
                   {
                       "type":"click",
                       "name":"客服",
                       "key":"FAQ"
                    },
                    {
                       "type":"click",
                       "name":"常见问题",
                       "key":"CJWT"
                    }]
              }
              ]
        }';
        echo $this->create_menu($post);
        echo $this->select_menu();
    }
    //验证消息
    public function valid()
    {
        if ($this->checkSignature()) {
            $echostr = $_GET['echostr'];
            echo $echostr;
            exit();
        } else {
            echo '验证失败';
            exit();
        }
    }
    //检查签名
        public function checkSignature()
        {
            //获取微信传递的4个参数$_GET
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $tmpArr = array($this->TOKEN, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                return true;
            } else {
                return false;
            }
        }

    //响应消息
        public function responseMsg()
        {
            $postData = file_get_contents('php://input');
            if (!$postData) {
                echo 'error-r';
                return false;
            }
            $object = simplexml_load_string($postData, "SimpleXMLElement", LIBXML_NOCDATA);
            $this->receiveEvent($object);
            //获取消息类型
            $MsgType = $object->MsgType;
            switch ($MsgType) {
                case 'event':
                    $this->receiveEvent($object);
                    break;
                case 'text':
                    $this->receiveText($object);
                    break;
                case 'image':
                    echo $this->receiveImage($object);
                    break;
                case 'voice':
                    echo $this->receiveVoice($object);
                    break;
                case 'video':
                    echo $this->receiveVideo($object);
                    break;
                case 'link':
                    echo $this->receiveLink($object);
                    break;
                case 'location':
                    echo $this->receiveLocation($object);
                    break;
            }
        }

    //接受事件推送
        public function receiveEvent($obj)
        {
            switch ($obj->Event) {
                //关注事件
                case 'subscribe':
                    switch ($obj->EventKey) {
                        case 'FAQ':
                            $content = '这是一个FAQ事件';
                            session(['pid'=>substr($obj->EventKey, 8)]);
                            echo $this->replyText($obj, $content);
                            break;
                        case '123':
                            $content = '我的参数是123，测试成功';
                            session(['pid'=>substr($obj->EventKey, 8)]);
                            echo $this->replyText($obj, $content);
                            break;
                        default:
                            $content = '欢迎关注商城';
                            $pid = substr($obj->EventKey, 8);
                            // $content = $this->test1();
                            session(['pid'=>$pid]);
                            echo $this->replyText($obj, session('pid'));
                            break;
                    }
                    break;
                //取消事件
                case 'unsubscribe':
                    break;
                //自定义菜单
                case 'CLICK':
                    switch ($obj->EventKey) {
                        case 'FAQ':
                            $content = '这是一个FAQ事件';
                            echo $this->replyText($obj, $content);
                            break;
                        case '123':
                            $content = '我的参数是123，测试成功';
                            echo $this->replyText($obj, $content);
                            break;
                        default:
                            $content = '第一次点击菜单';
                            echo $this->replyText($obj, $content);
                            break;
                    }
                    break;
            }
        }

    //回复文本消息
        public function replyText($obj, $content)
        {
            $replayXml = '<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        </xml>
                        ';
            //返回处理好的XML数据包
            $resultStr = sprintf($replayXml, $obj->FromUserName, $obj->ToUserName, time(), $content);
            return $resultStr;
        }


    //查询自定义菜单
        public function select_menu(){
            // 模拟GET请求
            $access_token = $this->get_access_token();
            $select_menu_url ='https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$access_token;
            return $this->httpRequest($select_menu_url);
        }

    //创建自定义菜单
        public function create_menu($post){
            // 模拟post请求
            $access_token = $this->get_access_token();
            $create_menu_url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;

            // return 132;
            return $this->httpRequest($create_menu_url,$post);
        }
        //图灵机器人 接入 函数
        public function tuling($content)
        {
            $url = "http://www.tuling123.com/openapi/api?key=90d8e3ff4a5d4624b33b31dffbf1379a&info=" . $content;
            $json = $this->httpRequest($url);
            $tulingArr = json_decode($json, true);
            return $tulingArr;
        }
        //获取用户信息
        public function getuserinfo($openid){
            $access_token = $this->get_access_token();
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $a = $this->httpRequest($url);
            $arr =json_decode($a,true);
            return $arr;


        }
        //发送客服消息
        public function send_kf_text($openid,$content){
            $access_token = $this->get_access_token();
            // 模拟post请求
            $post ='{
                    "touser":"'.$openid.'",
                    "msgtype":"text",
                    "text":
                    {
                         "content":"'.$content.'"
                    }
                }
                ';
            $send_kf_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
            $this->httpRequest($send_kf_url,$post);
            return $this->get_access_token();
        }
        public function get_access_token(){
            $access_token = $this->getAccessToken();
            return $access_token;
        }
        public function test1(){
            session(['pid'=>$pid]);
            dd(session('pid'));
        }
}

?>
